import 'dart:convert';

import 'package:fast_gbk/fast_gbk.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:myapp/state/bluetooth.dart';
import 'package:provider/provider.dart';
import 'package:flutter/services.dart';


class BlueServices extends StatefulWidget {
  const BlueServices({super.key});

  @override
  State<BlueServices> createState() => _Content();
}

class _Content extends State<BlueServices> {

  void showAlert(String title) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
            title: const Text('提示', style: TextStyle(fontSize: 20)),
            content: Text(title),
            actions: [TextButton(
              child: const Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            )]
        );
      },
    );
  }

  void _print(characteristic) async {

    List<String> lst = [];
    lst.add("! 0 200 200 400 1");
    lst.add("PW 400");
    lst.add("TEXT 5 0 10 100 测试打印纸张");
    lst.add("TEXT 5 0 10 140 打印成功");
    lst.add("TEXT 5 0 10 180 点击设置默认打印服务");

    lst.add("FORM");
    lst.add("PRINT");

    String command="";
    for (int i = 0; i < lst.length; ++i) {
      command+="${lst[i]}\r\n";
    }
    String base = base64Encode(gbk.encode(command));
    Uint8List bytes = base64.decode(base);

    try{
      await characteristic.write(bytes, withoutResponse: characteristic!.properties.writeWithoutResponse);
    } catch (err) {
      showAlert('指令写入失败,可以尝试使用其他服务写入！');
    }

  }

  @override
  Widget build(BuildContext context) {
    List<BluetoothService>? services = context.watch<BluetoothStore>().device?.servicesList;

    return Scaffold(
        appBar: AppBar(
          title: const Text('蓝牙服务信息',style: TextStyle(color: Colors.white, fontSize: 16)),
          toolbarHeight: 40,
          backgroundColor: Colors.deepPurple[300],
          centerTitle: true,
          iconTheme: const IconThemeData(color: Colors.white),
        ),
        body: Container(
          child: services == null
              ? _errView()
              : ListView(children: _buildServiceTiles(services, _print)),
        ));
  }

  Widget _errView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text(
            '没有可用的蓝牙服务',
            style: TextStyle(fontSize: 20),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('返回上一页'),
          ),
        ],
      ),
    );
  }

  List<Widget> _buildServiceTiles(services, print) {
    return services.map<Widget>((service) {
      return ExpansionTile(
        title: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            const Text('Service', style: TextStyle(color: Colors.blue)),
            Text('0x${service.uuid}'),
          ],
        ),
        children: service.characteristics.map<Widget>((characteristic) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ListTile(title: Text('Characteristic: 0x${characteristic.uuid}')),
              characteristic.properties.write ? Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const SizedBox(width: 20),
                  ElevatedButton(
                    onPressed: () {
                      print(characteristic);
                    },
                    child: const Text('打印'),
                  ),
                  const SizedBox(width: 20),
                  ElevatedButton(
                    onPressed: () {
                      context.read<BluetoothStore>().setCharacteristic(characteristic);
                    },
                    child: const Text('设为偏好'),
                  ),
                ],
              ) : const SizedBox()
             ],
          );
        }).toList(),
      );
    },
    ).toList();
  }
}
